<template>
  <el-tree ref="treeRef" :props="tree.props" :show-checkbox="props.showCheckBox"
    :default-expanded-keys="tree.defaultExpandedKeys" :data="tree.data" @currentChange="currentChange" node-key="id">
  </el-tree>
</template>
<script lang="ts" setup>
import { TreeKey } from 'element-plus/es/components/tree/src/tree.type';
import { nextTick } from 'vue';
import { ResourceService } from '~/service/sys';
import { ITreeNode } from '~/types/ui/tree/ITreeNode';
import elpUtil from '~/utils/elp';


export interface DeptTreeProps {
  autoSelectRoot?: boolean
  data?: ITreeNode[]
  currentNode?: ITreeNode
  showCheckBox?: boolean
}

const props = withDefaults(defineProps<DeptTreeProps>(), {
  autoSelectRoot: true,
  currentNode: null,
  showCheckBox: false
})

const tree = elpUtil.tree.defaultProps()
const treeRef = elpUtil.tree.createRef()

const emits = defineEmits(['currentChange', 'update:data'])

const currentChange = (node: ITreeNode) => {
  emits('currentChange', node)
}

const setCheckedKeys = function (keys: string[]) {
  treeRef.value!.setCheckedKeys(keys)
}

const getCheckedKeys = function (): string[] {
  return treeRef.value!.getCheckedKeys() as string[]
}

defineExpose({
  setCheckedKeys,
  getCheckedKeys
})


const query = () => {
  ResourceService.queryTree().then((nodes: ITreeNode[]) => {
    if (nodes.length === 1) tree.defaultExpandedKeys = [nodes[0].id]
    tree.data = nodes;
    emits('update:data', nodes)
    if (props.autoSelectRoot === true) {
      nextTick(() => {
        treeRef.value!.setCurrentKey(nodes[0][tree.nodeKey])
        emits('currentChange', nodes[0])
      })
    }
  })
}
query()
</script>
